// 密码强度验证工具
class PasswordValidator {
  static validatePassword(password) {
    const result = {
      isValid: false,
      strength: 0,
      messages: []
    };
    
    if (!password) {
      result.messages.push('密码不能为空');
      return result;
    }
    
    // 长度检查
    if (password.length < 6) {
      result.messages.push('密码长度至少6位');
    } else {
      result.strength += 1;
    }
    
    // 包含数字
    if (/\d/.test(password)) {
      result.strength += 1;
    } else {
      result.messages.push('密码应包含数字');
    }
    
    // 包含字母
    if (/[a-zA-Z]/.test(password)) {
      result.strength += 1;
    } else {
      result.messages.push('密码应包含字母');
    }
    
    // 包含特殊字符
    if (/[!@#$%^&*(),.?":{}|<>]/.test(password)) {
      result.strength += 1;
    } else if (password.length >= 8) {
      result.messages.push('建议包含特殊字符以增强安全性');
    }
    
    result.isValid = result.strength >= 2 && password.length >= 6;
    
    return result;
  }
  
  static getStrengthText(strength) {
    const texts = ['很弱', '弱', '中等', '强', '很强'];
    return texts[strength] || '很弱';
  }
  
  static getStrengthColor(strength) {
    const colors = ['danger', 'warning', 'info', 'success', 'success'];
    return colors[strength] || 'danger';
  }
  
  // 在密码输入框添加强度指示器
  static attachToInput(inputElement) {
    const container = inputElement.parentElement;
    
    // 创建强度指示器
    const strengthBar = document.createElement('div');
    strengthBar.className = 'password-strength mt-1';
    strengthBar.style.height = '4px';
    strengthBar.style.borderRadius = '2px';
    strengthBar.style.backgroundColor = '#e9ecef';
    strengthBar.style.transition = 'all 0.3s ease';
    
    const strengthText = document.createElement('div');
    strengthText.className = 'strength-text text-muted';
    strengthText.style.fontSize = '0.8em';
    strengthText.style.marginTop = '4px';
    
    container.appendChild(strengthBar);
    container.appendChild(strengthText);
    
    // 监听密码输入
    inputElement.addEventListener('input', function() {
      const validation = PasswordValidator.validatePassword(this.value);
      
      // 更新强度条
      const percentage = (validation.strength / 4) * 100;
      const color = PasswordValidator.getStrengthColor(validation.strength);
      
      strengthBar.style.background = `linear-gradient(to right, 
        var(--bs-${color}) ${percentage}%, 
        #e9ecef ${percentage}%)`;
      
      // 更新文本
      if (this.value) {
        const strengthLabel = PasswordValidator.getStrengthText(validation.strength);
        strengthText.innerHTML = `密码强度: <span class="text-${color}">${strengthLabel}</span>`;
        
        if (validation.messages.length > 0) {
          strengthText.innerHTML += '<br><small>' + validation.messages.join(', ') + '</small>';
        }
      } else {
        strengthText.textContent = '';
      }
    });
    
    return {
      validate: () => PasswordValidator.validatePassword(inputElement.value)
    };
  }
}
